package WordCount;


import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class WordCount {
    public static void main(String[] args) throws Exception {
        String inputPath ="F:\\大数据学习\\作业\\input\\file.txt";
        String outPath="F:\\大数据学习\\作业\\out";

        //获取flink运行环境
        ExecutionEnvironment executionEnvironment= ExecutionEnvironment.getExecutionEnvironment();
        //读取数据源
        DataSource<String> text = executionEnvironment.readTextFile(inputPath);
        //处理数据源
        FlatMapOperator<String, Tuple2<String, Integer>> wordAndOne = text.flatMap(new SplitClz());
        UnsortedGrouping<Tuple2<String, Integer>> groupedWordAndOne = wordAndOne.groupBy(0);
        AggregateOperator<Tuple2<String, Integer>> out = groupedWordAndOne.sum(1);

        //保存处理结果
        out.writeAsCsv(outPath,"\n"," ").setParallelism(1);

        executionEnvironment.execute();
    }

    static class SplitClz implements FlatMapFunction<String, Tuple2<String,Integer>>{

        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
            for(String word :s.split(" ")){
                 collector.collect(new Tuple2<>(word, 1));
            }
        }
    }
}
